package com.xianggu.trafficLimiter.impl;

import com.xianggu.trafficLimiter.TrafficLimiter;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author chengjy
 * @date 2025/3/25
 */

public class TokenBucketLimiter implements TrafficLimiter {

    private volatile long timeStamp = System.currentTimeMillis();
    private volatile long capacity = 100;// 桶的容量
    private volatile long rate = 100;// 令牌的放入速度
    private volatile AtomicLong tokens = new AtomicLong(20); // 当前令牌数量

    public TokenBucketLimiter() {
        new Thread(() -> {
        while (true) {
            try {
                Thread.sleep(1000);
                while (true){
                    long tokenSize = Math.min(capacity, tokens.get() + rate);
                    if(tokens.compareAndSet(tokens.get(), tokenSize)){
                        break;
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        }).start();
    }

    @Override
    public boolean limit() {
        long now = System.currentTimeMillis();
        // 先添加令牌
        timeStamp = now;
        System.out.println("当前时间："+now+" 当前桶内令牌数："+tokens.get());
        if (tokens.get() < 1) {
            // 桶内没有令牌，限流
            return true;
        }else {
            while (true){
                if (tokens.compareAndSet(tokens.get(), tokens.get() - 1)) {
                    return false;
                }
            }
        }
    }
}
